//  TinyConsole.swift
//  GerritHermes
//
//  Created by J.Zhou on 2020/3/15.
//  Copyright © 2020 周剑. All rights reserved.
//

import Cocoa

final class TinyConsole {
    static var shared = TinyConsole()
    let textView: NSTextView = {
        let textView = NSTextView()
        textView.backgroundColor = .black
        textView.isEditable = false
        textView.font = .systemFont(ofSize: 10)
        return textView
    }()

    static var textAppearance: [NSAttributedString.Key: Any] = {
        return [
            .font: NSFont(name: "Menlo", size: 8),
            .foregroundColor: NSColor.white
        ].compactMapValues({ $0 })
    }()

    private lazy var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .none
        formatter.timeStyle = .medium
        return formatter
    }()

    private var currentTimeStamp: String {
        return dateFormatter.string(from: Date())
    }

    // MARK: - Actions

    static func log(_ text: String, global: Bool = true) {
        DispatchQueue.main.async {
            let newLine = "\(text)\n"
            var str = shared.textView.string
            if str.count > 10000 {
                let startIndex = str.index(str.endIndex, offsetBy: -5000)
                str.removeSubrange(startIndex..<str.endIndex)
            }
            str.insert(contentsOf: newLine, at: shared.textView.string.startIndex)

            shared.textView.string = str
        }
    }

    static func clear() {
        DispatchQueue.main.async {
            shared.textView.string = ""
        }
    }
    
}

private extension NSAttributedString {
    static func breakLine() -> NSAttributedString {
        return NSAttributedString(string: "\n")
    }
}
